package com.xzit.rcpyxt.service.impl;

import com.xzit.rcpyxt.constant.MessageCode;
import com.xzit.rcpyxt.dto.*;
import com.xzit.rcpyxt.entity.Attendance;
import com.xzit.rcpyxt.entity.Class;
import com.xzit.rcpyxt.entity.Course;
import com.xzit.rcpyxt.entity.Historical;
import com.xzit.rcpyxt.entity.StudentAttendance;
import com.xzit.rcpyxt.exceptions.CustomeException;
import com.xzit.rcpyxt.mapper.AttendanceMapper;
import com.xzit.rcpyxt.mapper.ClassMapper;
import com.xzit.rcpyxt.mapper.HistoricalMapper;
import com.xzit.rcpyxt.mapper.StudentAttendanceMapper;
import com.xzit.rcpyxt.service.AttendanceService;
import com.xzit.rcpyxt.utils.PageUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AttendanceServiceImpl implements AttendanceService {

    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private AttendanceMapper attendanceMapper;
    @Autowired
    private StudentAttendanceMapper studentAttendanceMapper;
    @Autowired
    private HistoricalMapper historicalMapper;

    @Override
    public void rollCall (RollCallDto rollCallDto) {
        if (rollCallDto.getClassId() == null) {
            throw new CustomeException(MessageCode.PARAME_NOT_NULL_ERROR.getCode(), "班级id不能为空！");
        }
        if (rollCallDto.getTeacherId() == 0) {
            throw new CustomeException(MessageCode.PARAME_NOT_NULL_ERROR.getCode(), "老师id不能为空！");
        }
        Class aClass = classMapper.selectByPrimaryKey(rollCallDto.getClassId());
        if (aClass == null) {
            throw new CustomeException(MessageCode.DATA_NOT_EXISTS_ERROR.getCode(), "班级不存在！");
        }
        String className = aClass.getName();
        Integer classGrade = aClass.getGrade();
        String attendanceName = classGrade + "-" + className;

        SaveAttendanceDto attendance = new SaveAttendanceDto();
        attendance.setName(attendanceName);
        attendance.setClassId(aClass.getId());
        attendance.setTeacherId(rollCallDto.getTeacherId());
        attendance.setRemark(rollCallDto.getRemark());
        if (rollCallDto.getStudentAttendanceInfoList() != null && rollCallDto.getStudentAttendanceInfoList().size() > 0) {
            int attendance0 = 0, attendance1 = 0, attendance2 = 0;
            for ( StudentAttendanceRequest.StudentAttendanceInfo studentAttendanceInfo: rollCallDto.getStudentAttendanceInfoList()) {
                switch (studentAttendanceInfo.getAttendanceStatus()) {
                    case 0:
                        attendance0 += 1;
                        break;
                    case 1:
                        attendance1 += 1;
                        break;
                    case 2:
                        attendance2 += 1;
                        break;
                }
            }
            attendance.setArrived(attendance0);
            attendance.setAbsence(attendance1);
            attendance.setAbsenteeism(attendance2);
            insertByAttendance(attendance);
        } else {
            throw new CustomeException(MessageCode.PARAME_NOT_NULL_ERROR.getCode(), "考勤人员不能为空！");
        }
    }

    @Override
    public void insertByAttendance(SaveAttendanceDto attendance) {
        if (StringUtils.isBlank(attendance.getName())) {
            throw new CustomeException(MessageCode.PARAME_NOT_NULL_ERROR.getCode(), "考勤名称不能为空！");
        }
        int success = attendanceMapper.insertByAttendance(attendance);
        if (success < 1) {
            throw new CustomeException(MessageCode.SYSTEM_ERROR.getCode(), "保存考勤失败！");
        }

        Historical historical = new Historical();
        historical.setType(0);
        historical.setUserId(attendance.getTeacherId());
        historical.setTitle("考勤");
        historical.setContent("您对" + attendance.getName() + "进行了考勤!");
        historicalMapper.insertByHistorical(historical);

        if (attendance.getStudentAttendanceInfoList() != null && attendance.getStudentAttendanceInfoList().size() > 0) {
            StudentAttendanceRequest studentAttendanceRequest = new StudentAttendanceRequest();
            studentAttendanceRequest.setAttendanceId(attendance.getId());
            studentAttendanceRequest.setAttendanceName(attendance.getName());
            studentAttendanceRequest.setStudentAttendanceInfoList(attendance.getStudentAttendanceInfoList());
            rollCall(studentAttendanceRequest);
        }
    }

    @Override
    public PageUtil findByAttendanceList (AttendanceListRequest attendanceDto) {
        int page = attendanceDto.getPage();
        int pageSize = attendanceDto.getPageSize();
        attendanceDto.setPage(page - 1);
        attendanceDto.setPageSize(page * pageSize);
        List<Attendance> teachers = attendanceMapper.selectByAttendanceList(attendanceDto);
        int totalElements = attendanceMapper.countByAttendanceList(attendanceDto);
        return new PageUtil(page, pageSize, totalElements, teachers);
    }

    /**
     * 保存学生考勤信息
     * @param studentAttendanceRequest
     */
    private void rollCall (StudentAttendanceRequest studentAttendanceRequest) {
        List<StudentAttendanceRequest.StudentAttendanceInfo> studentAttendanceInfos = studentAttendanceRequest.getStudentAttendanceInfoList();
        StudentAttendance studentAttendance = null;
        for ( StudentAttendanceRequest.StudentAttendanceInfo studentAttendanceInfo: studentAttendanceInfos) {
            studentAttendance = new StudentAttendance();
            BeanUtils.copyProperties(studentAttendanceInfo, studentAttendance);
            studentAttendance.setAttendanceId(studentAttendanceRequest.getAttendanceId());
            studentAttendanceMapper.insertByStudengAttendance(studentAttendance);

            Historical historical = new Historical();
            historical.setType(1);
            historical.setUserId(studentAttendance.getStudentId());
            historical.setTitle("考勤");
            switch (studentAttendanceInfo.getAttendanceStatus()) {
                case 0:
                    historical.setContent(studentAttendanceRequest + "对您考勤成功!");
                    break;
                case 1:
                    historical.setContent(studentAttendanceRequest + "对您考勤记为请假!");
                    break;
                case 2:
                    historical.setContent(studentAttendanceRequest + "对您考勤记为缺勤!");
                    break;
            }
            historicalMapper.insertByHistorical(historical);
        }
    }

    @Override
    public PageUtil findByAttendanceUserList (StudentAttendanceListRequest studentAttendanceListRequest) {
        int page = studentAttendanceListRequest.getPage();
        int pageSize = studentAttendanceListRequest.getPageSize();
        studentAttendanceListRequest.setPage(page - 1);
        studentAttendanceListRequest.setPageSize(page * pageSize);
        List<StudentAttendance> teachers = studentAttendanceMapper.selectByAttendanceIdList(studentAttendanceListRequest);
        int totalElements = studentAttendanceMapper.countByAttendanceIdList(studentAttendanceListRequest);
        return new PageUtil(page, pageSize, totalElements, teachers);
    }

    public static Date[] getDayDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        Date endDate = calendar.getTime();
        return new Date[] { startDate, endDate };
    }

    private static SimpleDateFormat initFormat(String format) {
        SimpleDateFormat mDateFormat = new SimpleDateFormat(format);
        return mDateFormat;
    }

    @Override
    public PageUtil findByHistoricalList (HistoricalListRequestDto historicalListRequestDto) {
        int page = historicalListRequestDto.getPage();
        int pageSize = historicalListRequestDto.getPageSize();
        historicalListRequestDto.setPage(page - 1);
        historicalListRequestDto.setPageSize(page * pageSize);
        String createTime = historicalListRequestDto.getCurrentTime();
        Date[] dayDate = null;
        if(createTime != null){
            try {
                dayDate = getDayDate(initFormat("yyyy-MM-dd").parse(createTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            dayDate = getDayDate(new Date());
        }
        historicalListRequestDto.setStartTime(dayDate[0]);
        historicalListRequestDto.setEndTime(dayDate[1]);
        List<Historical> teachers = historicalMapper.selectByHistoricalList(historicalListRequestDto);
        int totalElements = historicalMapper.countByHistoricalList(historicalListRequestDto);
        return new PageUtil(page, pageSize, totalElements, teachers);
    }

}